package cn.aukw.todolist;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

import cn.aukw.todolist.adapter.ListAdapter;
import cn.aukw.todolist.bean.ListBean;
import cn.aukw.todolist.utils.DBUtils;

public class MainActivity extends AppCompatActivity {

    private List<ListBean> list = new ArrayList<>();
    private ListAdapter adapter;
    private DBUtils dbUtils;
    private RecyclerView rv_list;
    private ImageView iv_add;
    private TextView tv_main_title;
    private ActivityResultLauncher launcher;

    private SoundPool soundPool;
    public int soundComplete;
    private int soundDelete;

    private static final String CHANNEL_ID = "todo_channel_id";
    private static final int NOTIFICATION_PERMISSION_CODE = 123;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initSoundEffects();
        initLauncher();
        init();
        createNotificationChannel();
        checkNotificationPermission();
        startTodoService();
    }


    private void init() {
        dbUtils = new DBUtils(this);
        tv_main_title = findViewById(R.id.tv_main_title);
        tv_main_title.setText("待办事项");
        rv_list = findViewById(R.id.rv_list);
        iv_add = findViewById(R.id.iv_add);
        rv_list.setLayoutManager(new LinearLayoutManager(this));

        adapter = new ListAdapter(this, new ListAdapter.ItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ListBean bean = list.get(position);
                Intent intent = new Intent(MainActivity.this, RecordActivity.class);
                intent.putExtra("id", bean.getId());              //事件的id
                intent.putExtra("title", bean.getTitle());       //事件的标题
                intent.putExtra("content", bean.getContent());  //事件的内容
                intent.putExtra("time", bean.getTime());         //记录事件的时间
                // 跳转到修改记录界面
                launcher.launch(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {
                showDeleteDialog(position);
            }
        }, (taskId, isCompleted) -> {
            // 更新数据库中的任务完成状态
            dbUtils.updateListCompleted(taskId, isCompleted);
            // 获取项的当前位置，并重新排序
            int oldPosition = findTaskPositionById(taskId);
            sortTaskList();
            int newPosition = findTaskPositionById(taskId);

            // 更新 UI，只移动已排序的项，避免刷新整个列表
            if (oldPosition != newPosition) {
                int startPosition = Math.min(oldPosition, newPosition);
                int itemCount = Math.abs(oldPosition - newPosition) + 1;
                adapter.notifyItemRangeChanged(startPosition, itemCount);
//                adapter.notifyItemMoved(oldPosition, newPosition);
            } else {
                //考虑它无需改变位置的情况
                adapter.notifyItemChanged(newPosition);
            }


        });
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, RecordActivity.class);
                launcher.launch(intent);
            }
        });
        showQueryData();
    }

    private void showDeleteDialog(int position) {
        AlertDialog dialog;
        View customView = getLayoutInflater().inflate(R.layout.dialog_custom, null);
        TextView title = customView.findViewById(R.id.dialog_title);
        Button positiveButton = customView.findViewById(R.id.dialog_positive_button);
        Button negativeButton = customView.findViewById(R.id.dialog_negative_button);

        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.CustomAlertDialogTheme);
        builder.setView(customView);
        dialog = builder.create();

        positiveButton.setOnClickListener(v -> {
            ListBean bean = list.get(position);
            if (dbUtils.deleteList(bean.getId())) {
                list.remove(position);
                adapter.notifyItemRemoved(position);
                Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                playSound(soundDelete);
            }
            dialog.dismiss();
        });

        negativeButton.setOnClickListener(v -> dialog.dismiss());
        dialog.show();
    }

    private int findTaskPositionById(int taskId) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getId() == taskId) {
                return i;
            }
        }
        return -1; // 没找到
    }


    private void initLauncher() {
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult o) {
                int resultCode = o.getResultCode();
                if (resultCode == 2) {
                    showQueryData();
                }
            }
        });
    }

    private void showQueryData() {
        if (list == null) {
            list = new ArrayList<>();
        } else {
            list.clear();
        }
        list = dbUtils.queryList();
        sortTaskList();
        adapter.setData(list);
        rv_list.setAdapter(adapter);
    }

    private void sortTaskList() {
        // 未完成的任务在前，已完成的任务在后
        list.sort((o1, o2) -> Boolean.compare(o1.isCompleted(), o2.isCompleted()));
    }

    private void initSoundEffects() {
        // 初始化 SoundPool，根据系统版本区分处理
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();
            soundPool = new SoundPool.Builder()
                    .setMaxStreams(2) // 同时最多播放2个音效
                    .setAudioAttributes(audioAttributes)
                    .build();
        } else {
            // 旧版本
            soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
        }

        // 加载音效到 SoundPool
        soundComplete = soundPool.load(this, R.raw.complete_sound, 1);
        soundDelete = soundPool.load(this, R.raw.delete_sound, 1);
    }

    public void playSound(int soundId) {
        soundPool.play(soundId, 1, 1, 0, 0, 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (soundPool != null) {
            soundPool.release();
            soundPool = null;
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    "todo_channel_id",
                    "待办事项提醒",
                    NotificationManager.IMPORTANCE_LOW // 优先级低，不发出声音
            );
            channel.setDescription("常驻显示待办事项提醒");
//            Log.println(Log.WARN, "Notification", "创建通知渠道");
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    private void checkNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.POST_NOTIFICATIONS},
                        NOTIFICATION_PERMISSION_CODE);
            }
        }
    }

    private void startTodoService() {
        Intent intent = new Intent(this, TodoService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent); // Android 8.0+ 启动前台服务
        } else {
            startService(intent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == NOTIFICATION_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限获取成功，启动服务
                startTodoService();
            }
        }
    }

}